package com.supermarket.api.service.impl;

import com.supermarket.api.bean.shop.ShopProductReq;
import com.supermarket.api.common.PageParam;
import com.supermarket.api.entity.ProductEntity;
import com.supermarket.api.entity.ShopEntity;
import com.supermarket.api.enums.ShopStatusType;
import com.supermarket.api.repository.ProductRepository;
import com.supermarket.api.repository.ShopRepository;
import com.supermarket.api.service.ShopService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * 店铺服务层
 * @author 李其伟
 * @date 2023/10/16
 */
@Slf4j
@Service
public class ShopServiceImpl implements ShopService {

    @Autowired
    private ShopRepository shopRepository;

    @Autowired
    private ProductRepository productRepository;

    @Override
    public List<ShopEntity> topList(Integer number) {
        PageParam pageParam = new PageParam();
        pageParam.setPageSize(number);
        Page<ShopEntity> page = this.list(pageParam);
        return page.getContent();
    }

    @Override
    public Page<ShopEntity> list(PageParam pageParam) {
        Sort sort = Sort.by(Sort.Direction.DESC, "sort");
        Pageable pageable = PageRequest.of(pageParam.getPageNum() , pageParam.getPageSize(), sort);
        return shopRepository.findAllByShopStatus(ShopStatusType.SUCCESS.getStatus(),pageable);
    }

    @Override
    public ShopEntity detail(Long shopId) {
        Optional<ShopEntity> optional = shopRepository.findById(shopId);
        return optional.orElseGet(ShopEntity::new);
    }

    @Override
    public Page<ProductEntity> productList(ShopProductReq req) {
        Sort sort = Sort.by(Sort.Direction.DESC, "sort");
        Pageable pageable = PageRequest.of(req.getPageNum() , req.getPageSize(), sort);
        return productRepository.findAllByShopId(req.getShopId(),pageable);
    }

}
